package jpb.command;

import jpb.Assert;
import jpb.CommandArg;
import jpb.StartupCommandSelector;

import java.io.File;

import static jpb.Assert.notNull;

/**
 * <p>
 * A startup command selector that reads the 'JAVA_HOME' environment variable and tries to figure out java command
 * location based on that. It does not perform dry run, but it validates that the command is present as a file
 * in the operating system. 
 *
 * @author Dariusz Kordonski
 */
public class JavaHomeSelector implements StartupCommandSelector {

    private static final String JAVA_HOME = "JAVA_HOME";
    private static final String JAVA_HOME_PATH_SUFFIX = File.separator + "bin" + File.separator + "java";

    /**
     * Represents environment variables of the current Java process.
     *
     */
    public static interface ProcessEnvironment {

        /**
         * Get environment variable of given <tt>name</tt>.
         *
         * @param name of the variable
         * @return value of the variable, or <code>null</code>, if it does not exist in the current environment
         */
        String get(String name);
    }

    private static class DefaultEnvironment implements ProcessEnvironment {

        @Override
        public String get(String name) {
            return System.getenv(name);
        }
    }

    private final ProcessEnvironment environment;

    public JavaHomeSelector(ProcessEnvironment environment) {
        this.environment = notNull("environment", environment);
    }

    public JavaHomeSelector() {
        this(new DefaultEnvironment());
    }

    @Override
    public CommandArg command()
    {
        final String javaHome = environment.get(JAVA_HOME);
        if (javaHome == null) {
            return CommandArg.empty();
        }
        final File javaHomeDir = new File(javaHome);
        if (javaHomeDir.isDirectory()) {
            return CommandArg.of(javaHomeDir.getAbsolutePath() + JAVA_HOME_PATH_SUFFIX);
        }
        return CommandArg.empty();
    }
}
